var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// 启动websocket服务器编程 , 配置websocket 服务器，并进行问题控制
    var WebSocketServer = require("ws").Server ;
    var wss =  new WebSocketServer({port:8888});
    var users = {};
    wss.on("connection",function (connection) {
        console.log("user connected");
        // 连接后进行服务器传输 ，  修改连接处理器
        connection.on("message",function (message) {
            console.log("message--->"+message)
            var data ;
            try {
                data = JSON.parse(message);
            } catch (e) {
                console.log("解析消息错误!")
                data = {} ;
            }
          console.log("go message",message);

            // 定义消息登录控制
            switch (data.type){
                case "login":
                    console.log("User logged in as ",data.name);

                    if(users[data.name]){
                        sendTo(connection,{type:"login",sucess:false});
                    }else{
                        users[data.name] = connection ;
                        connection.name = data.name ;
                        sendTo(connection,{type:"login",sucess:true});
                    }
                    break ;
                // 添加请求 offer处理器
                case "offer": console.log(data.name+"请求---> ");
                    var conn = users[data.name];
                    // 监测用户是否在服务器上
                    if(conn != null){
                        // 如果存在 则发送offer细节 ， 也为用户的connection属性上添加一个属性，便于以后能方便的获取
                        connection.otherName = data.name ;
                        sendTo(conn,{type:"offer",offer:data.offer,name:connection.name});
                    }
                    break ;
                // 添加应答 answer 处理器
                case "answer":console.log("发送应答--->"+data.name);
                    var conn = users[data.name];
                    if(conn != null){
                        // 如果存在 则发送answer细节 ， 也为用户的connection属性上添加一个属性，便于以后能方便的获取
                        connection.otherName = data.name ;
                        sendTo(conn,{type:"answer",answer:data.answer});
                    }
                    break ;

                //处理ICE候选路径问题
                case "candidate":console.log("ICE候选路径--- Send candidate to>"+data.name);
                    var conn = users[data.name];
                    if(conn != null){
                        sendTo(conn,{type:"candidate",candidate:data.candidate});
                    }
                    break ;

                // 呼叫挂断
                case  "leave":console.log("呼叫挂断--- disconnecting user form >"+data.name);
                     var conn = users[data.name];
                    conn.otherName = null ;
                    if(conn != null){
                        sendTo(connection,{type:"leave"});
                    }
                    break ;
                default : sendTo(connection,{type:"error",message:"Unrecognized command: "+data.type});
                    break ;
            };
        });

        // 当连接断了之后来删除用户
        connection.on("close",function () {

            // 当呼叫挂断后 ， 进行处理
            if(connection.name){
                console.log(connection.name+"user 退出");
                delete users[connection.name];

                //
                if(connection.otherName){
                    console.log("Disconnecting user form ",connection.otherName);
                        var conn = users[connection.otherName];
                    if(conn!=null){
                        sendTo(connection,{type:"leave"});
                    }
                }

            }



        });

        function  sendTo(conn , message) {
            conn.send(JSON.stringify(message));
        }
    });



module.exports = app;
